package kr.ac.skhu.m.controller;

import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.ac.skhu.m.data.BoardComment;
import kr.ac.skhu.m.data.BoardData;
import kr.ac.skhu.m.util.EncodingUtil;
import kr.ac.skhu.m.util.PaggingUtil;
import kr.ac.skhu.m.util.StringUtil;
import kr.ac.skhu.m.value.NoticeListValue;
import net.htmlparser.jericho.Element;
import net.htmlparser.jericho.HTMLElementName;
import net.htmlparser.jericho.Source;

import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

public class BoardC extends AbstractController {
	
	private String mode;
	private String menu;
	private String successView;
	private String bsid;
	private String searchBun1;
	private String searchBun2;
	private String type;
	private String useComment;
	
	public void setMode(String mode) {
		this.mode = mode;
	}

	public void setMenu(String menu) {
		this.menu = menu;
	}

	public void setSuccessView(String successView) {
		this.successView = successView;
	}

	public void setBsid(String bsid) {
		this.bsid = bsid;
	}

	public void setSearchBun1(String searchBun1) {
		this.searchBun1 = searchBun1;
	}
	
	public void setSearchBun2(String searchBun2) {
		this.searchBun2 = searchBun2;
	}
	public void setType(String type) {
		this.type = type;
	}
	public void setUseComment(String useComment) {
		this.useComment = useComment;
	}

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		ModelAndView mav = null;
		
		if(mode.equals("list")){
			mav = list(request, response);
		}else{
			mav = view(request, response);
		}
		
		return mav;
	}
	
	protected ModelAndView list(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		ModelAndView mav = new ModelAndView(successView);
		
		//요청이 get방식인지 post방식인지 구분한다.
		boolean isGet = request.getMethod().equals("GET");
		
		/**
		 * 요청 파라미터
		 */
		//게시판 분류 ... 대학과 대학원을 분류한다.
		String searchBun = ServletRequestUtils.getStringParameter(request, "searchBun", searchBun1);
		//현재 페이지
		String currentPage = ServletRequestUtils.getStringParameter(request, "curPage", "1");
		//검색 타입
		String searchType = ServletRequestUtils.getStringParameter(request, "searchType", "1");
		//검색어
		String searchWord = isGet ? EncodingUtil.getParamterSafely(request.getQueryString(), "searchWord") : ServletRequestUtils.getStringParameter(request, "searchWord", "");
		//검색어를 ECU-KR로 인코딩
		String srchWord = URLEncoder.encode(searchWord, "EUC-KR");
		
		//URL 생성
		String url = "http://www.skhu.ac.kr/board/boardlist.aspx?bsid=" + bsid +"&searchBun=" + searchBun + "&curpage=" + currentPage + 
				"&searchType=" + searchType + "&searchWord=" + srchWord;
		
		/**
		 * 목록 생성
		 */
		BoardData boardData = new BoardData(url, type);
		List<NoticeListValue> valueList = boardData.getNoticeListValue();
		
		/**
		 * 페이징 정보
		 */
		int intTypeCurPage = boardData.getIntTypeCurPage();
		int intTypeTotalPage = boardData.getIntTypeTotalPage();
		PaggingUtil paggingUtil = new PaggingUtil(intTypeCurPage, intTypeTotalPage);
		
		/**
		 * 게시판의 분류가 대학과 대학원으로 나누어져있으면  searchBun을 응답으로 보낸다.
		 */
		if(StringUtil.isEmpty(searchBun2)){
			mav.addObject("isSearchBun", false);
		}else{
			mav.addObject("isSearchBun", true);
			mav.addObject("searchBun1", searchBun1);
			mav.addObject("searchBun2", searchBun2);
		}
		
		mav.addObject("listSize", valueList.size());
		mav.addObject("valueList", valueList);
		mav.addObject("searchBun", searchBun);
		mav.addObject("paggingUtil", paggingUtil);
		mav.addObject("searchType", searchType);
		mav.addObject("searchWord", searchWord);
		mav.addObject("menu", menu);
		
		return mav;
	}
	
	protected ModelAndView view(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		
		ModelAndView mav = new ModelAndView(successView);
		
		boolean isGet = request.getMethod().equals("GET");
		
		String searchBun = ServletRequestUtils.getStringParameter(request, "searchBun", searchBun1);
		String currentPage = ServletRequestUtils.getStringParameter(request, "curPage", "1");
		String searchType = ServletRequestUtils.getStringParameter(request, "searchType", "1");
		String searchWord = isGet ? EncodingUtil.getParamterSafely(request.getQueryString(), "searchWord") : ServletRequestUtils.getStringParameter(request, "searchWord", "");
		
		//송장 번호와 cj택배에 배송추적 관련 주소와 연결 시킨다.
		String url = "http://www.skhu.ac.kr/board/boardread.aspx?idx=" + request.getParameter("idx") + "&bsid=" + bsid + "&searchBun=" + searchBun + "&curpage=" + currentPage;

		//해당 URL 페이지를 가져온다.
		Source source = new Source(new URL(url));

		//메소드 찾기를 위해 시작부터 끝까지 태그들만 parse 한다 (?)
		source.fullSequentialParse();
		
		/**
		 * 내용
		 */
		Element element = source.getAllElementsByClass("board_view_con").get(0);
		String content = element.toString();
		//if(!content.matches("(http://|https://){1}[\\w\\.\\-/:?&%#=]+")){
		if(!content.contains("href=\"http://") && !content.contains("href='http://")){
			content = content.replace("href=\"", "href=\"http://www.skhu.ac.kr");
			content = content.replace("href='", "href='http://www.skhu.ac.kr");
		}
		if(!content.contains("src=\"http://") && !content.contains("src='http://")){
			content = content.replace("src=\"", "src=\"http://www.skhu.ac.kr");
			content = content.replace("src='", "src='http://www.skhu.ac.kr");
		}
		 
		/**
		 * 제목
		 */
		Element title_el = source.getElementById("ctl00_ContentPlaceHolder1_ctl00_lbTitle");
		String title = title_el.getTextExtractor().toString();
		
		/**
		 * 작성자
		 */
		Element writer_el = source.getElementById("ctl00_ContentPlaceHolder1_ctl00_lbWriter");
		String writer = writer_el.getTextExtractor().toString();
		
		/**
		 * 작성일
		 */
		Element date_el = source.getElementById("ctl00_ContentPlaceHolder1_ctl00_lbDate");
		String date = date_el.getTextExtractor().toString();
		
		//답변
		if(type.equals("qna")){
			Element element2 = source.getAllElementsByClass("board_view_con").get(1);
			String answer = element2.toString();
			mav.addObject("answer", answer);
		}
		
		/**
		 * 첨부파일
		 */		
		if(!type.equals("qna")){
			Element span = source.getElementById("ctl00_ContentPlaceHolder1_ctl00_lbFile");
			List<Element> a = span.getAllElements(HTMLElementName.A);
			if(a.size() > 0){
				String file = a.get(0).toString();
				file = file.replace("href=\"", "href=\"http://www.skhu.ac.kr");
				file = file.replace("href='", "href='http://www.skhu.ac.kr");
				file = file.replace("src=\"", "src=\"http://www.skhu.ac.kr");
				file = file.replace("src='", "src='http://www.skhu.ac.kr");
				mav.addObject("file", file);
			}	
		}
		
		/**
		 * 댓글
		 */
		List<BoardComment> boardCommentList = new ArrayList<BoardComment>();
		
		if(useComment.equalsIgnoreCase("y")){
			
			List<Element> commentList = source.getAllElementsByClass("comment_cont");
			int commentListSize = commentList.size();
			
			for(int i=0; i<commentListSize; i++){
				if( (i%2) == 0 ){
					
					BoardComment boardComment = new BoardComment();
					
					String author = commentList.get(i).getAllElementsByClass("author").get(0).getTextExtractor().toString();
					String regDate = commentList.get(i).getAllElementsByClass("date").get(0).getTextExtractor().toString();
					String dscComment = commentList.get(i).getAllElementsByClass("dsc_comment").get(0).getTextExtractor().toString();
					dscComment = dscComment.replace("<p>", "");
					dscComment = dscComment.replace("</p>", "");
					
					boardComment.setAuthor(author);
					boardComment.setDate(regDate);
					boardComment.setDscComment(dscComment);
					
					boardCommentList.add(boardComment);
					
				}
			}
			
			
		}
		
		mav.addObject("title", title);
		mav.addObject("writer", writer);
		mav.addObject("date", date);
		mav.addObject("content", content);
		mav.addObject("searchBun", searchBun);
		mav.addObject("currentPage", currentPage);
		mav.addObject("searchType", searchType);
		mav.addObject("searchWord", searchWord);
		mav.addObject("menu", menu);
		mav.addObject("boardCommentList", boardCommentList);
		mav.addObject("boardCommentListSize", boardCommentList.size());
		
		return mav;
	}
	
}

